package com.zhongxi.guoyuan.fragment;


import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.adapter.CategoryAdapter;
import com.zhongxi.guoyuan.adapter.personCenter.ClearWeedExchangeAdapter;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.base.BaseFragment;
import com.zhongxi.guoyuan.entity.BaseResponse;
import com.zhongxi.guoyuan.entity.clearweed.ClearWeedGood;
import com.zhongxi.guoyuan.entity.clearweed.ClearWeedResult;
import com.zhongxi.guoyuan.entity.projectItem.ProjectItemData;
import com.zhongxi.guoyuan.entity.projectItem.ProjectItemResult;
import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.utils.CommonTool;
import com.zhongxi.guoyuan.utils.ToastUtil;
import com.zhongxi.guoyuan.utils.UiUtils;
import com.zhongxi.guoyuan.view.MainActivity;
import com.zhongxi.guoyuan.view.MainHomeActivity;
import com.zhongxi.guoyuan.view.beanExchange.ExchangeCateActivity;
import com.zhongxi.guoyuan.view.personalCenter.ClearWeedDetailActivity;
import com.zhongxi.guoyuan.view.personalCenter.ClearWeedSearchActivity;
import com.zhongxi.guoyuan.view.rewardCoin.HMActivity;
import com.zhongxi.guoyuan.widget.goldshop.NoScrollGridView;
import com.zhongxi.guoyuan.widget.view.MyScrollView;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;


public class ExchangeHomeFragment extends BaseFragment implements MyScrollView.OnScrollListener, ClearWeedExchangeAdapter.OnItemClickListener {


    @Bind(R.id.ivBack)
    ImageView mIvBack;
    @Bind(R.id.tvTitle)
    TextView mTvTitle;
    @Bind(R.id.rl)
    RelativeLayout mRl;
    @Bind(R.id.tv_exchangehome_category)
    TextView mTvExchangehomeCategory;
    @Bind(R.id.rl_exchangehome_search)
    RelativeLayout mRlExchangehomeSearch;
    @Bind(R.id.recycleview)
    RecyclerView mRecycleview;
    @Bind(R.id.tv_exchangehome_new)
    TextView mTvExchangehomeNew;
    @Bind(R.id.tv_exchangehome_hot)
    TextView mTvExchangehomeHot;
    @Bind(R.id.tv_exchangehome_recent)
    TextView mTvExchangehomeRecent;
    @Bind(R.id.linear_began)
    LinearLayout lienarBegan;
    @Bind(R.id.linear_scrollbody)
    LinearLayout linearScrollbody;
    @Bind(R.id.linear_stop)
    LinearLayout linearStop;
    @Bind(R.id.myscrollview)
    MyScrollView mScrollView;
    @Bind(R.id.button)
    Button button;
    @Bind(R.id.button2)
    Button button2;
    @Bind(R.id.linear_top_image)
    RelativeLayout lineartopimage;

    private int orderby = 0;

    private ClearWeedExchangeAdapter adapter;
    private List<ClearWeedGood> list = new ArrayList<>();
    private String longitude;
    private String latitude;
    private LinearLayoutManager layoutManager;
    private ClearWeedResult clearWeedResult;
    private String type;
    private String mCateid = "0";
    private ArrayList<ProjectItemData> mProjectItemDataList = new ArrayList<>();
    private JSONObject storeInfo;
    private int height;
    private PopupWindow popupWindow;


    private View.OnKeyListener backListener = new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_BACK) {
                if (!TextUtils.isEmpty(mPaysuccess)) {
                    startAct(MainHomeActivity.class);
                    return true;
                } else {
                    return false;
                }
            }
            return false;
        }
    };
    private String mPaysuccess;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View mView = inflater.inflate(R.layout.fragment_exchange_home, container, false);
        ButterKnife.bind(this, mView);
        if (getArguments() != null) {
            mPaysuccess = getArguments().getString("paysuccess");
        }
        mView.setFocusable(true);
        mView.setFocusableInTouchMode(true);
        mView.setOnKeyListener(backListener);
        return mView;
    }

    @Override
    protected void initView() {
        super.initView();
        initTitle();
        tvTitle.setText("豆豆兑换");

        ViewTreeObserver mViewTreeObserver = lineartopimage.getViewTreeObserver();
        mViewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                height = lineartopimage.getHeight();
            }
        });
    }


    @Override
    protected void initData() {
        super.initData();
        //禁止recycleview活动，防止滑动卡顿
        layoutManager = new LinearLayoutManager(getContext()) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };

        mRecycleview.setLayoutManager(layoutManager);

        longitude = MyApplication.getInstance().getLongitude();
        latitude = MyApplication.getInstance().getLatitude();
        adapter = new ClearWeedExchangeAdapter(getContext());
        mRecycleview.setAdapter(adapter);
        mTvExchangehomeNew.setSelected(true);
        mProjectItemDataList.add(0, new ProjectItemData("0", "全部", "", true));
        getCate();
    }

    private void getCate() {
        type = "cate";
        getServer(Url.CLEARWEED_CATE, null, "", false, null, "get");
    }

    public void getData() {
        type = "data";
        String str = "&page=" + pageNum + "&orderBy=" + orderby + "&cateid=" + mCateid + "&lng=" + longitude + "&lat=" + latitude;
        getServer(Url.CLEARWEED_GOODLIST, null, str, false, null, "get");
    }

    @Override
    protected void processSuccessResult(String response) {
        super.processSuccessResult(response);
        Gson gson = new Gson();
        if (type.equals("cate")) {
            ProjectItemResult itemResult = gson.fromJson(response, ProjectItemResult.class);
            MyApplication.getInstance().setSpValue(itemResult.getSafeobj());
            if (itemResult.getData() != null && itemResult.getData().size() > 0) {
                mProjectItemDataList.addAll(itemResult.getData());
//                setCateList();
            }
            getData();
        } else if (type.equals("data")) {
            clearWeedResult = gson.fromJson(response, ClearWeedResult.class);
            MyApplication.getInstance().setSpValue(clearWeedResult.getSafeobj());
            if (pageNum == 1) {
                list.clear();
            }
            if (clearWeedResult.getGoodsInfo() != null && clearWeedResult.getGoodsInfo().size() > 0) {
                list.addAll(clearWeedResult.getGoodsInfo());
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    storeInfo = jsonObject.optJSONObject("store");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                adapter.setList(list, storeInfo);

            } else {
                if (pageNum > 2) {
                    adapter.setFooter_state(2);
                } else {
                    adapter.setFooter_state(0);
                }

                pageNum--;
                if (pageNum < 1) {
                    pageNum = 1;
                }

                adapter.notifyDataSetChanged();

            }

        }
    }

    @Override
    protected void ProcessFailResult(String response) {
        super.ProcessFailResult(response);
        Gson gson = new Gson();
        BaseResponse baseResponse = gson.fromJson(response, BaseResponse.class);
        MyApplication.getInstance().setSpValue(baseResponse.getSafeobj());

        if (baseResponse.getCode() == 1000) {
            adapter.setFooter_state(0);
            adapter.notifyDataSetChanged();
        }
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        mScrollView.setOnScrollListener(this);
        adapter.setItemClickListener(this);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ToastUtil.show(UiUtils.getString(R.string.noline));
            }
        });
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ((MainActivity) getActivity()).currentIndex = 3;
                ((MainActivity) getActivity()).index = 1;
                ((MainActivity) getActivity()).refresh();

            }
        });
    }

    @OnClick({R.id.ivBack, R.id.tv_exchangehome_category, R.id.rl_exchangehome_search, R.id.tv_exchangehome_new, R.id.tv_exchangehome_hot, R.id.tv_exchangehome_recent})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ivBack:
                getActivity().finish();
                if (!TextUtils.isEmpty(mPaysuccess)) {
                    startAct(MainHomeActivity.class);
                }
                break;
            case R.id.tv_exchangehome_category:

//                getPopupwindow(view);
                Intent intent = new Intent(context, ExchangeCateActivity.class);
                intent.putExtra("exchange", mProjectItemDataList);
                startActivity(intent);
                break;
            case R.id.rl_exchangehome_search:
                startAct(ClearWeedSearchActivity.class);
                break;
            case R.id.tv_exchangehome_new:
                pageNum = 1;
                orderby = 0;
                setColor(mTvExchangehomeNew, mTvExchangehomeHot, mTvExchangehomeRecent);
                getData();
                break;
            case R.id.tv_exchangehome_hot:
                pageNum = 1;
                orderby = 1;
                setColor(mTvExchangehomeHot, mTvExchangehomeNew, mTvExchangehomeRecent);
                getData();
                break;
            case R.id.tv_exchangehome_recent:
                pageNum = 1;
                orderby = 2;
                setColor(mTvExchangehomeRecent, mTvExchangehomeNew, mTvExchangehomeHot);
                getData();
                break;
        }
    }

    public void setColor(TextView view1, TextView view2, TextView view3) {
        view1.setTextColor(getResources().getColor(R.color.title_red));
        view2.setTextColor(getResources().getColor(R.color.gohere));
        view3.setTextColor(getResources().getColor(R.color.gohere));
    }

    private void getPopupwindow(View v) {
        View popView = View.inflate(context, R.layout.pop_reward_window, null);
        WindowManager wm = (WindowManager) getActivity().getSystemService(Context.WINDOW_SERVICE);
        int width = wm.getDefaultDisplay().getWidth() * 10 / 11;
        popView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        popupWindow = new PopupWindow(popView, width, -2, true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.setFocusable(true);
        int[] location = new int[2];
        v.getLocationInWindow(location);  //将v相对屏幕的坐标存入int数组中 int[0] 为 x轴 int[1]为y轴
        Animation animation = AnimationUtils.loadAnimation(context, R.anim.popupwindow);
        popView.startAnimation(animation);
        popupWindow.showAtLocation(v, Gravity.NO_GRAVITY, location[0], location[1] + v.getWidth() * 1 / 4);
        NoScrollGridView gv_category = (NoScrollGridView) popView.findViewById(R.id.gv_category);
        CategoryAdapter adapter = new CategoryAdapter(getActivity(), mProjectItemDataList);
        gv_category.setAdapter(adapter);
        gv_category.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                Intent intent = new Intent(context, ExchangeCateActivity.class);
                intent.putExtra("index", position);
                startActivity(intent);
                popupWindow.dismiss();
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    public void onScroll(int scrollY) {
        if (scrollY >= height) {
            if (linearScrollbody.getParent() != linearStop) {
                lienarBegan.removeView(linearScrollbody);
                lienarBegan.setLayoutParams(new LinearLayout.LayoutParams(linearScrollbody.getMeasuredWidth(), linearScrollbody.getMeasuredHeight()));

                linearStop.addView(linearScrollbody);
            }
        } else {
            if (linearScrollbody.getParent() != lienarBegan) {
                linearStop.removeView(linearScrollbody);
                lienarBegan.addView(linearScrollbody);
            }
        }
    }

    @Override
    public void scrollBottom() {
        if (CommonTool.isFirstScroll()) {
            pageNum++;
            getData();
        }
    }

    @Override
    public void onClick(View view, int position) {
        Intent intent = new Intent(getContext(), ClearWeedDetailActivity.class);
        intent.putExtra("id", list.get(position).getId());
        startActivity(intent);
    }
}
